package com.qyhl.webtv.commonlib.utils.view.video.smallvideo;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.R;
import com.qyhl.webtv.commonlib.constant.AppConfigConstant;
import com.qyhl.webtv.commonlib.utils.config.AppConfigUtil;
import com.qyhl.webtv.commonlib.utils.view.video.detailvideo.MOrientationUtils;
import com.qyhl.webtv.commonlib.utils.view.video.view.ProgressWheel;
import com.shuyu.gsyvideoplayer.utils.Debuger;
import com.shuyu.gsyvideoplayer.utils.NetworkUtils;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.shuyu.gsyvideoplayer.video.base.GSYBaseVideoPlayer;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;

import moe.codeest.enviews.ENPlayView;

/**
 * Created by qyhl on 2018/4/25.
 * 小视频栏目播放器样式
 */

public class QYSVideoPlayer extends StandardGSYVideoPlayer {
    //网络状态
    private TextView netStatus;

    //当前时间
    private TextView currentTime;

    //亮度进度
    protected ProgressBar mBrightnessDialogProgress;

    //音量图标
    private ImageView volumeIcon;

    //播放量
    private TextView playNum;

    //封面时长
    private TextView playTime;

    private ProgressWheel progressWheel;

    public QYSVideoPlayer(Context context, Boolean fullFlag) {
        super(context, fullFlag);
    }

    public QYSVideoPlayer(Context context) {
        super(context);
    }

    public QYSVideoPlayer(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public int getLayoutId() {
        return R.layout.qy_small_video_player;
    }

    @Override
    protected void init(Context context) {
        super.init(context);
        netStatus = (TextView) findViewById(R.id.network_status);
        currentTime = (TextView) findViewById(R.id.time);
        progressWheel = (ProgressWheel) findViewById(R.id.load_status);
        playNum = (TextView) findViewById(R.id.play_num);
        playTime = (TextView) findViewById(R.id.video_time);
        if (mIfCurrentIsFullscreen) {
            netStatus.setVisibility(VISIBLE);
            currentTime.setVisibility(VISIBLE);
            getBackButton().setVisibility(VISIBLE);
        } else {
            netStatus.setVisibility(GONE);
            currentTime.setVisibility(GONE);
            getBackButton().setVisibility(GONE);
        }
        findViewById(getPlayStatusId()).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCurrentState == CURRENT_STATE_PAUSE) {
                    clickStartIcon();
                } else {
                    if (NetworkUtils.isWifiConnected(mContext)) {
                        startPlayLogic();
                    } else {
                        showWifiDialog();
                    }
                }
            }
        });
    }

    @Override
    protected void resolveFullVideoShow(Context context, final GSYBaseVideoPlayer gsyVideoPlayer, final FrameLayout frameLayout) {
        if (Build.VERSION.SDK_INT != Build.VERSION_CODES.O) {
            super.resolveFullVideoShow(context, gsyVideoPlayer, frameLayout);
        } else {
            LayoutParams lp = (LayoutParams) gsyVideoPlayer.getLayoutParams();
            lp.setMargins(0, 0, 0, 0);
            lp.height = -1;
            lp.width = -1;
            lp.gravity = 17;
            gsyVideoPlayer.setLayoutParams(lp);
            gsyVideoPlayer.setIfCurrentIsFullscreen(true);
            this.mOrientationUtils = new MOrientationUtils((Activity) context, gsyVideoPlayer);
            this.mOrientationUtils.setEnable(this.mRotateViewAuto);
            this.mOrientationUtils.setRotateWithSystem(this.mRotateWithSystem);
            Class<? extends GSYBaseVideoPlayer> aClass = gsyVideoPlayer.getClass();
            try {
                Field mOrientationUtils = aClass.getDeclaredField("mOrientationUtils");
                mOrientationUtils.setAccessible(true);
                mOrientationUtils.set(gsyVideoPlayer, this.mOrientationUtils);
            } catch (NoSuchFieldException | IllegalAccessException e) {
                e.printStackTrace();
            }
            if (this.isShowFullAnimation()) {
                this.postDelayed(new Runnable() {
                    public void run() {
                        if (mLockLand && mOrientationUtils.getIsLand() != 1) {
                            mOrientationUtils.resolveByClick();
                        }

                        gsyVideoPlayer.setVisibility(VISIBLE);
                        frameLayout.setVisibility(VISIBLE);
                    }
                }, 300L);
            } else {
                if (this.mLockLand) {
                    this.mOrientationUtils.resolveByClick();
                }

                gsyVideoPlayer.setVisibility(VISIBLE);
                frameLayout.setVisibility(VISIBLE);
            }

            if (this.mVideoAllCallBack != null) {
                Debuger.printfError("onEnterFullscreen");
                this.mVideoAllCallBack.onEnterFullscreen(this.mOriginUrl, new Object[]{this.mTitle, gsyVideoPlayer});
            }

            this.mIfCurrentIsFullscreen = true;
            this.checkoutState();
        }
    }

    @Override
    protected void updateStartImage() {
        if (mStartButton instanceof ENPlayView) {
            ENPlayView enPlayView = (ENPlayView) mStartButton;
            enPlayView.setDuration(500);
            if (mCurrentState == CURRENT_STATE_PLAYING) {
                enPlayView.play();
            } else if (mCurrentState == CURRENT_STATE_ERROR) {
                enPlayView.pause();
            } else {
                enPlayView.pause();
            }
        } else if (mStartButton instanceof ImageView) {
            ImageView imageView = (ImageView) mStartButton;
            if (mCurrentState == CURRENT_STATE_PLAYING) {
                imageView.setImageResource(R.drawable.qy_video_pause);
            } else {
                imageView.setImageResource(R.drawable.qy_video_play);
            }
        }
    }

    /**
     * 设置播放量
     *
     * @param num
     */
    public void setPlayNum(String num) {
        if (num != null && num.contains("播放")) {
            num = num.substring(0, num.length() - 2);
        }
        try {
            int minPlay = (int) AppConfigUtil.getInstance().getConValue(AppConfigConstant.MIN_PLAY) ;
            if (minPlay == 0) {
                playNum.setVisibility(View.GONE);
            } else {
                //判断评论数是否大于最少浏览数
                if (StringUtils.isEmpty(num)) {
                    playNum.setVisibility(View.GONE);
                } else if (Integer.parseInt(num) >=
                        minPlay) {
                    playNum.setText(StringUtils.transformNum(num) + "播放");
                    playNum.setVisibility(View.VISIBLE);
                } else {
                    playNum.setVisibility(View.GONE);
                }
            }

        } catch (Exception e) {
            playNum.setVisibility(View.GONE);
        }
    }

    public void setPlayTime(String duration) {
        if (TextUtils.isEmpty(duration)) {
            playTime.setVisibility(GONE);
            playTime.setText("");
        } else {
            playTime.setVisibility(VISIBLE);
            playTime.setText(duration);
        }
    }

    /**
     * 全屏收起按钮
     *
     * @return
     */
    @Override
    public int getShrinkImageRes() {
        return R.drawable.qy_video_to_normal_selector;
    }

    /**
     * 全屏展开按钮
     *
     * @return
     */
    @Override
    public int getEnlargeImageRes() {
        return R.drawable.qy_video_to_fullscreen_selector;
    }

    /**
     * 获取封面播放按钮状态
     *
     * @return
     */
    protected int getPlayStatusId() {
        return R.id.play_status;
    }

    protected int getBottomId() {
        return R.id.layout_bottom;
    }

    @Override
    public void startPlayLogic() {
        super.startPlayLogic();
        findViewById(getPlayStatusId()).setVisibility(GONE);
    }

    @Override
    public void onAutoCompletion() {
        super.onAutoCompletion();
        findViewById(getPlayStatusId()).setVisibility(VISIBLE);
        findViewById(getBottomId()).setVisibility(INVISIBLE);
    }

    @Override
    protected void touchSurfaceUp() {
        super.touchSurfaceUp();
        if (mIfCurrentIsFullscreen) {
            setFullTopUI(mContext);
        }
    }

    @Override
    protected void changeUiToPreparingShow() {
        super.changeUiToPreparingShow();
        if (findViewById(getPlayStatusId()) != null) {
            findViewById(getPlayStatusId()).setVisibility(GONE);
        }
        if (progressWheel != null) {
            progressWheel.setVisibility(VISIBLE);
        }

        if (playTime != null) {
            playTime.setVisibility(GONE);
        }

    }

    @Override
    protected void changeUiToPlayingShow() {
        super.changeUiToPlayingShow();
        if (findViewById(getPlayStatusId()) != null) {
            findViewById(getPlayStatusId()).setVisibility(GONE);
        }
        if (progressWheel != null) {
            progressWheel.setVisibility(GONE);
        }

        if (playTime != null) {
            playTime.setVisibility(GONE);
        }

    }

    @Override
    protected void changeUiToPlayingBufferingShow() {
        super.changeUiToPlayingBufferingShow();
        if (progressWheel != null) {
            progressWheel.setVisibility(VISIBLE);
        }

        if (playTime != null) {
            playTime.setVisibility(GONE);
        }
    }

    //

    @Override
    protected void changeUiToNormal() {
        super.changeUiToNormal();
        if (findViewById(getPlayStatusId()) != null && !mIfCurrentIsFullscreen) {
            findViewById(getPlayStatusId()).setVisibility(VISIBLE);
        }

        if (progressWheel != null) {
            progressWheel.setVisibility(GONE);
        }
    }

    @Override
    protected void changeUiToCompleteShow() {
        super.changeUiToCompleteShow();
        if (playTime != null) {
            playTime.setVisibility(VISIBLE);
        }
    }

    /**
     * 设置全屏顶部内容
     */
    private void setFullTopUI(Context context) {
        //网络状态
        netStatus.setText(NetUtil.getNetWorkTypeName(context));

        //当前时间
        currentTime.setText(new SimpleDateFormat("HH:mm").format(System.currentTimeMillis()));
    }

    protected int getVolumeIconId() {
        return R.id.qy_video_volume_img;
    }


    protected int getVolumeLayoutId() {
        return R.layout.video_volume_dialog_qy;
    }


    protected int getBrightnessLayoutId() {
        return R.layout.video_light_dialog_qy;
    }


    protected int getVolumeProgressId() {
        return R.id.volume_progressbar;
    }


    protected int getBrightnessTextId() {
        return R.id.app_video_brightness;
    }

    @Override
    protected void showProgressDialog(float deltaX, String seekTime, int seekTimePosition, String totalTime, int totalTimeDuration) {
        if (mProgressDialog == null) {
            View localView = LayoutInflater.from(getActivityContext()).inflate(R.layout.video_progress_dialog_qy, null);
            mDialogProgressBar = ((ProgressBar) localView.findViewById(R.id.duration_progressbar));
            if (mDialogProgressBarDrawable != null) {
                mDialogProgressBar.setProgressDrawable(mDialogProgressBarDrawable);
            }
            mDialogSeekTime = ((TextView) localView.findViewById(R.id.tv_current));
            mDialogTotalTime = ((TextView) localView.findViewById(R.id.tv_duration));
            mDialogIcon = ((ImageView) localView.findViewById(R.id.duration_image_tip));
            mProgressDialog = new Dialog(getActivityContext(), R.style.video_style_dialog_progress);
            mProgressDialog.setContentView(localView);
            mProgressDialog.getWindow().addFlags(Window.FEATURE_ACTION_BAR);
            mProgressDialog.getWindow().addFlags(32);
            mProgressDialog.getWindow().addFlags(16);
            mProgressDialog.getWindow().setLayout(getWidth(), getHeight());
            if (mDialogProgressNormalColor != -11) {
                mDialogTotalTime.setTextColor(mDialogProgressNormalColor);
            }
            if (mDialogProgressHighLightColor != -11) {
                mDialogSeekTime.setTextColor(mDialogProgressHighLightColor);
            }
            WindowManager.LayoutParams localLayoutParams = mProgressDialog.getWindow().getAttributes();
            localLayoutParams.gravity = Gravity.TOP;
            localLayoutParams.width = getWidth();
            localLayoutParams.height = getHeight();
            int[] location = new int[2];
            getLocationOnScreen(location);
            localLayoutParams.x = location[0];
            localLayoutParams.y = location[1];
            mProgressDialog.getWindow().setAttributes(localLayoutParams);
        }
        if (!mProgressDialog.isShowing()) {
            mProgressDialog.show();
        }

        mDialogSeekTime.setText(seekTime);
        mDialogTotalTime.setText(" / " + totalTime);
        if (totalTimeDuration > 0) {
            mDialogProgressBar.setProgress(seekTimePosition * 100 / totalTimeDuration);
        }
        if (deltaX > 0) {
            mDialogIcon.setBackgroundResource(com.shuyu.gsyvideoplayer.R.drawable.video_forward_icon);
        } else {
            mDialogIcon.setBackgroundResource(com.shuyu.gsyvideoplayer.R.drawable.video_backward_icon);
        }
    }

    @Override
    protected void dismissProgressDialog() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }

    @Override
    protected void showVolumeDialog(float deltaY, int volumePercent) {
        if (mVolumeDialog == null) {
            View localView = LayoutInflater.from(getActivityContext()).inflate(getVolumeLayoutId(), null);
            if (localView.findViewById(getVolumeProgressId()) instanceof ProgressBar) {
                mDialogVolumeProgressBar = ((ProgressBar) localView.findViewById(getVolumeProgressId()));
                if (mVolumeProgressDrawable != null && mDialogVolumeProgressBar != null) {
                    mDialogVolumeProgressBar.setProgressDrawable(mVolumeProgressDrawable);
                }
            }
            volumeIcon = (ImageView) localView.findViewById(getVolumeIconId());
            mVolumeDialog = new Dialog(getActivityContext(), com.shuyu.gsyvideoplayer.R.style.video_style_dialog_progress);
            mVolumeDialog.setContentView(localView);
            mVolumeDialog.getWindow().addFlags(8);
            mVolumeDialog.getWindow().addFlags(32);
            mVolumeDialog.getWindow().addFlags(16);
            mVolumeDialog.getWindow().setLayout(-2, -2);
            WindowManager.LayoutParams localLayoutParams = mVolumeDialog.getWindow().getAttributes();
            localLayoutParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.TOP;
            localLayoutParams.width = getWidth();
            localLayoutParams.height = getHeight();
            int[] location = new int[2];
            getLocationOnScreen(location);
            localLayoutParams.x = location[0];
            localLayoutParams.y = location[1];
            mVolumeDialog.getWindow().setAttributes(localLayoutParams);
        }
        if (volumeIcon != null) {
            if (volumePercent < 1) {
                volumeIcon.setImageResource(R.drawable.qy_video_volume_silence);
            } else {
                volumeIcon.setImageResource(R.drawable.qy_video_volume_normal);
            }
        }

        if (!mVolumeDialog.isShowing()) {
            mVolumeDialog.show();
        }
        if (mDialogVolumeProgressBar != null) {
            mDialogVolumeProgressBar.setProgress(volumePercent);
        }
    }

    @Override
    protected void dismissVolumeDialog() {
        if (mVolumeDialog != null) {
            mVolumeDialog.dismiss();
            mVolumeDialog = null;
        }
    }

    @Override
    protected void showBrightnessDialog(float percent) {
        if (mBrightnessDialog == null) {
            View localView = LayoutInflater.from(getActivityContext()).inflate(getBrightnessLayoutId(), null);
            if (localView.findViewById(getBrightnessTextId()) instanceof ProgressBar) {
                mBrightnessDialogProgress = (ProgressBar) localView.findViewById(getBrightnessTextId());
            }
            mBrightnessDialog = new Dialog(getActivityContext(), com.shuyu.gsyvideoplayer.R.style.video_style_dialog_progress);
            mBrightnessDialog.setContentView(localView);
            mBrightnessDialog.getWindow().addFlags(8);
            mBrightnessDialog.getWindow().addFlags(32);
            mBrightnessDialog.getWindow().addFlags(16);
            mBrightnessDialog.getWindow().setLayout(-2, -2);
            WindowManager.LayoutParams localLayoutParams = mBrightnessDialog.getWindow().getAttributes();
            localLayoutParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.TOP;
            localLayoutParams.width = getWidth();
            localLayoutParams.height = getHeight();
            int[] location = new int[2];
            getLocationOnScreen(location);
            localLayoutParams.x = location[0];
            localLayoutParams.y = location[1];
            mBrightnessDialog.getWindow().setAttributes(localLayoutParams);
        }
        if (!mBrightnessDialog.isShowing()) {
            mBrightnessDialog.show();
        }
        if (mBrightnessDialogProgress != null) {
            mBrightnessDialogProgress.setProgress((int) (percent * 100));
        }
    }

    @Override
    protected void dismissBrightnessDialog() {
        if (mBrightnessDialog != null) {
            mBrightnessDialog.dismiss();
            mBrightnessDialog = null;
        }
    }

    @Override
    protected void cloneParams(GSYBaseVideoPlayer from, GSYBaseVideoPlayer to) {
        super.cloneParams(from, to);
        QYSVideoPlayer sf = (QYSVideoPlayer) from;
        QYSVideoPlayer st = (QYSVideoPlayer) to;

        if (st.playNum != null) {
            st.setPlayNum(sf.playNum.getText().toString());
        }

    }

}
